package code;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>
 *
 * </p>
 *
 * @author xiaovcloud
 * @since 2021/8/21 下午9:05
 */
public class ThreadABCTest {
	public static void main(String[] args) throws Exception {
//		Thread threadA = new Thread(() -> {
//			System.out.println("A");
//		});
//		Thread threadB = new Thread(() -> {
//			try {
//				threadA.join();
//				System.out.println("B");
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
//		});
//		Thread threadC = new Thread(() -> {
//			try {
//				threadB.join();
//				System.out.println("C");
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
//		});
//
//		threadA.start();
//		threadB.start();
//		threadC.start();
		printTenTimes();
	}

	/**
	 * 编程实现三个线程ABC，并让它们顺次打印 ABC 十次
	 */
	private static void printTenTimes() {
		final AtomicInteger token = new AtomicInteger(0);
		final Thread threadA = new Thread() {
			@Override
			public void run() {
				for (int i = 0; i < 10; i++) {
					while (token.get() % 3 != 0) {
						Thread.yield();       // 不是 A 运行的时候, 让出执行权
					}
					System.out.print("A");
					token.incrementAndGet();  // 由于增加 1 后被 3 模余数 1, 而被 3 模余数 1 是 B 可以运行的, 此步相当于把令牌传递给 B
				}
			}
		};
		final Thread threadB = new Thread() {
			@Override
			public void run() {
				for (int i = 0; i < 10; i++) {
					while (token.get() % 3 != 1) {
						Thread.yield();
					}
					System.out.print("B");
					token.incrementAndGet();
				}
			}
		};
		final Thread threadC = new Thread() {
			@Override
			public void run() {
				for (int i = 0; i < 10; i++) {
					while (token.get() % 3 != 2) {
						Thread.yield();
					}
					System.out.print("C");
					token.incrementAndGet();
				}
			}
		};
		threadA.start();
		threadB.start();
		threadC.start();
	}

}

